<?php

use backend\utils\AppUtil;
use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $father_name string */
/* @var $model object */
$editor_id = uniqid();
$this->registerJsFile('@web/js/tinymce/tinymce.min.js', ['depends' => ['backend\assets\AppAsset']]);

?>
<div id="success-note" class="notification submit-success png_bg" style="display:none;">
    <div></div>
</div>

<div id="error-note" class="notification errorshow png_bg">
    <div>
        <?php
        echo AppUtil::get_error_msg($model)
        ?>
    </div>
</div>

<div style="width: 90%;margin-right: auto;margin-left: auto" class="teams-form">

    <?php $form = ActiveForm::begin([
        "options" => [
            'id' => 'dataForm',
        ],
        'enableAjaxValidation' => true,
        'validationUrl' => 'validate-rich-text',
    ]); ?>

    <div><?= $model->attributeLabels()['name'] ?></div>
    <?php $ueditor = "<textarea id='tinymce-{$editor_id}-name' >{$model['name']}</textarea>"; ?>
    <?= $form->field($model, 'name', ['template' => "{label}\n{$ueditor}{input}\n{hint}\n{error}", 'options' => ['style' => 'position:relative;']])
        ->textarea(['rows' => 0, 'style' => 'width:800px; position:absolute; top:-40px; opacity:0;display:none', 'class' => 'details_text width260',])
        ->label(false) ?>

    <div><?= $model->attributeLabels()['description'] ?></div>
    <?php $ueditor = "<textarea id='tinymce-{$editor_id}-description' >{$model['description']}</textarea>"; ?>
    <?= $form->field($model, 'description', ['template' => "{label}\n{$ueditor}{input}\n{hint}\n{error}", 'options' => ['style' => 'position:relative;']])
        ->textarea(['rows' => 0, 'style' => 'width:800px; position:absolute; top:-40px; opacity:0;display:none', 'class' => 'details_text width260',])
        ->label(false) ?>

    <?php if ($model->uuid) { ?>
        <?= Html::hiddenInput('uuid', $model->uuid, ['id' => 'info_uuid']); ?>
    <?php } else { ?>
    <?php } ?>

    <div class="form-group" style="height: 40px;">
        <?= Html::submitButton($model->isNewRecord ? '添加' : '更新', ['class' => $model->isNewRecord ? 'btn btn-primary pull-right' : 'btn btn-primary pull-right']) ?>
    </div>

    <?php ActiveForm::end(); ?>

</div>
<?php

$Js = <<<JS
// 编辑器配置数组
const editorConfigs = [
    {
        id: '{$editor_id}-name',
        placeholder: '<p style="color:silver">（30 字以内）</p>',
        wordlimit: 30,
        input_id: 'formproject-name',
    },
    {
        id: '{$editor_id}-description',
        placeholder: '<p style="color:silver">（300 字以内）</p>',
        wordlimit: 300,
        input_id: 'formproject-description',
    },
];

// 创建一个通用的 setup 函数
function setup(editor, placeholder, callback, wordlimit) {
    editor.on('init', function () {
        var regex = /^(\s)*$|^<p>(&nbsp;\s*)*<\/p>$/g;
        if (editor.getContent().match(regex)) {
            editor.setContent(placeholder); // 确保编辑器不为空，以便显示占位符
        }
    });
    editor.on('focus', function () {
        var localHtml = editor.getContent();
        if ($.trim(localHtml).indexOf("silver") > -1 && $($.trim(localHtml)).text() === $($.trim(placeholder)).text()) {
            editor.setContent(''); // 清除占位符内容
        }
    });
    editor.on('blur', function () {
        var content = editor.getContent();
        if (callback) {
            callback();
        }
        var regex = /^(\s)*$|^<p>(&nbsp;\s*)*<\/p>$/g;
        if (content.match(regex)) {
            editor.setContent(placeholder); // 重新显示占位符
        }
    });

    // 获得焦点时清除占位符
    editor.on('focus', function () {
        var localHtml = editor.getContent();
        if ($.trim(localHtml).indexOf("silver") > -1 && $($.trim(localHtml)).text() === $($.trim(placeholder)).text()) {
            editor.setContent(''); // 清除占位符内容
        }
    });
    editor.on('wordCountUpdate', function () {
        var wordCount = editor.plugins.wordcount.getCount();
        var container = editor.editorContainer;
        var buttonParent = $(container).find("button[class*=wordcount]").parent();
        if (buttonParent.next().length == 0) {
            buttonParent.after('<div class="tox-statusbar__right-container-my wordcount"></div>');
        }
        if (wordCount > wordlimit) {
            $(container).find(".wordcount").html('<span style="color:red;">字数超出最大允许值，服务器可能拒绝保存！</span>');
        } else {
            $(container).find(".wordcount").html('当前已输入' + wordCount + '个字, 您还可以输入' + (wordlimit - wordCount) + '个字。');
        }
    });

}

// 图片上传处理函数
function image_upload_handler(blobInfo, success, failure) {
    // 这里是图片上传逻辑，你可以根据需要修改
    console.log('上传图片:', blobInfo.filename());
    success('...'); // 返回图片URL
}

// 循环生成编辑器
$(document).ready(function () {
    editorConfigs.forEach(config => {
        tinymce.init({
            selector: 'textarea#tinymce-'+config.id,
            setup: function (editor) {
                setup(editor, config.placeholder, function () {
                    const content = document.getElementById(config.input_id);//摘要id
                    const wordCount = editor.plugins.wordcount.getCount();
                    const wordCountEl = $('#word-count-'+config.id);
                    // 更新字数显示
                    wordCountEl.text('字数:'+wordCount/config.wordlimit);

                    // 检查字数限制
                    if (wordCount > config.wordlimit) {
                        content.value = 'tooLong';
                    } else {
                        let content_text = editor.getContent({format: 'text'})
                        console.log(content_text);
                        content.value = content_text;
                    }

                    // 触发blur事件
                    $(content).trigger("blur");
                }, config.wordlimit);
            },
            license_key: 's4l9wh65t7kwumbps2umxxwr0whg3hw2cpnjwz5s26gm3kgf',
            plugins: [
                'advlist',
                'searchreplace',
                'table',
                'image',
                'media',
                'link',
                'code',
                'fullscreen',
                'wordcount'
            ],
            toolbar: false,
            elementpath: false,
            height: 100,
            language: 'zh_CN',
            menubar: '',
            branding: false,
            promotion: false,
            images_upload_handler: image_upload_handler
        });
    });
});
JS;
$this->registerJs($Js);

?>

<script>
</script>
